
const generateVideoFrames = Module.cwrap('generateVideoFrames', 'number', ['string'])
const getImageBuffer = Module.cwrap('getImage', 'number', ['number'])

// 获取视频的所有帧图片
export const getAllFramePicture = async (file) => {
  const imageInfos = []
  const fileBuffer = await fileToUint8Array(file);
  const filePath = `/${file.name}`
  FS.writeFile(filePath, fileBuffer)
  const videoFrameCount = generateVideoFrames(filePath)
  FS.unlink(filePath)
  for(let i = 0; i < videoFrameCount; i++) {
    const imageBinaryData = getImageBuffer(i)
    const imageInfo = getImageInfo(imageBinaryData)
    imageInfos.push(imageInfo)
  }
  return imageInfos
}

// 获取视频文件有多少帧
export const getVideoFrameCount = async (file) => {
  const fileBuffer = await fileToUint8Array(file);
  const filePath = `/${file.name}`
  FS.writeFile(filePath, fileBuffer)
  const videoFrameCount = generateVideoFrames(filePath)
  FS.unlink(filePath)
  return videoFrameCount
}

// 获取视频第index帧的图片
export const getVideoFramePictureByIndex = async (file, index) => {
  if(index < 0) {
    return null
  }
  const fileBuffer = await fileToUint8Array(file);
  const filePath = `/${file.name}`
  FS.writeFile(filePath, fileBuffer)
  const videoFrameCount = generateVideoFrames(filePath)
  FS.unlink(filePath)
  if(index > videoFrameCount) {
    return null
  }
  const imageBinaryData = getImageBuffer(index)
  const imageInfo = getImageInfo(imageBinaryData)
  return imageInfo
}

function getImageInfo(imgDataPtr) {
  let width = Module.HEAPU32[imgDataPtr / 4],
      height = Module.HEAPU32[imgDataPtr / 4 + 1],
      imageBufferPtr = Module.HEAPU32[imgDataPtr / 4 + 2],
      imageBuffer = Module.HEAPU8.slice(imageBufferPtr, imageBufferPtr + width * height * 3);
  // Module._free(imgDataPtr);
  // Module._free(imageBufferPtr);
  const imageDataBuffer = new Uint8ClampedArray(width * height * 4);
  let j = 0;
  for (let i = 0; i < imageBuffer.length; i++) {
    if (i && i % 3 == 0) {
      imageDataBuffer[j] = 255;
      j += 1;
    }
    imageDataBuffer[j] = imageBuffer[i];
    j += 1;
  }
  return {
    width,
    height,
    imageDataBuffer
  };
}

function fileToUint8Array(file) {
  return fileToBuf(file).then(buff => {
    return new Uint8Array(buff)
  })
}

function fileToBuf(file){
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = (event) => {
      if(event.target.error) {
        reject(event.target.error)
      } else {
        resolve(event.target.result)
      }
    }
    reader.onerror = (e) => {
      reject(e)
    }
  })
}
